<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
// Models
use App\Models\Machine;
use App\Models\Region;
use App\Models\SpecialNumber;

class MachineController extends Controller
{
    //
    public function register(Request $request) {
        $validator = Validator::make($request->all(), [
    		'machine_number' => 'required',
    		'password' => 'required|string|max:255|min:8',
    	]);

    	if ($validator->fails()) {
    		return response()->json(["status" => 400, "message" => config('messages.required_param')], 200);
        }
        //  如果查找到，更新密码
        $find_machine = Machine::where('machine_number', $request->machine_number)
                        ->first();
        if ($find_machine){
            $find_machine ->update([
                'password' => $request->password,
            ]);
            return response()->json(["status" => 200, "message" => ""], 200);
        }
        $machine = Machine::forceCreate([
            'machine_number' => $request->machine_number,
            'password' => $request->password,
            'api_token' => Str::random(80),
        ]);

        return response()->json(["status" => 200, "data" => $machine, "message" => ""], 200);
    }

    public function login(Request $request) {
        $validator = Validator::make($request->all(), [
    		'machine_number' => 'required',
    		'password' => 'required|string|max:255|min:8',
        ]);
        
    	if ($validator->fails()) {
            return response()->json(["status" => 400, "message" => config('messages.required_param')], 200);
        }
        
        $machine = Machine::where('machine_number', $request->machine_number)
                        ->first();

        if (!$machine) {
            return response()->json(["status" => 400, "messages" => ""], 200);
        }

        $hash_ma = Hash::make($machine->machine_number);
        $hash_pw = Hash::make($machine->password);
        
        if (!Hash::check($request->password, $hash_pw) || !Hash::check($request->machine_number, $hash_ma)){
            return response()->json(["status" => 400,"data" => $machine, "messages" => ""], 200);
        }

        $machine->is_online = true;
        $machine->last_ping = strtotime("now");
        $machine->save();

        $data["machine"] = $machine;
        $data["regions"] = Region::with("specialNumbers")->get();
        $todayTimeLimits = Region::select("region_name", 'start' . date("w") . ' AS start', 'end' . date("w") . ' AS end', 'disable' . date("w") . ' AS disable')->get();
        $timeLimits = [];
        foreach($todayTimeLimits as $todayTimeLimit) {
            array_push($timeLimits, array(
                'regsion_name' => $todayTimeLimit->region_name,
                'start' => date("Y-m-d ") . $todayTimeLimit->start,
                'end' => date("Y-m-d ") . $todayTimeLimit->end,
                'disable' => $todayTimeLimit->disable,
            ));
        }
        $data["todayTimeLimit"] = $timeLimits;

        return response()->json(["status" => 200, "data" => $data, "message" => ""], 200);
    }

    public function ping(Request $request)
    {
        if($request->machine_number) {
            $time = $request->time;//app传的日期
            if (preg_match ("/^([0-9]{2})-([0-9]{2})-([0-9]{4})$/", $time, $parts))
            {
                //检测是否为日期
                if(!checkdate($parts[2],$parts[1],$parts[3])) {
                    return response()->json(["status" => 400, "data" => null, "message" => "date format is error"], 200);
                }
            } else {
                return response()->json(["status" => 400, "data" => null, "message" => "date format is error"], 200);
            }
            
            $machine = Machine::where("machine_number", $request->machine_number)->first();
            
            $machine->is_online = true;
            $machine->last_ping = strtotime("now");
            $machine->save();

            $w = date("w",strtotime($time));
            $data["machine"] = $machine;
            $data["regions"] = Region::with("specialNumbers")->get();
            $todayTimeLimits = Region::select("region_name", 'start' . $w . ' AS start', 'end' . $w . ' AS end', 'disable' . $w . ' AS disable')->get();
            $timeLimits = [];
            foreach($todayTimeLimits as $todayTimeLimit) {
                array_push($timeLimits, array(
                    'regsion_name' => $todayTimeLimit->region_name,
                    'start' => $parts[3].'-'.$parts[2].'-'.$parts[1].' ' . $todayTimeLimit->start,
                    'end' => $parts[3].'-'.$parts[2].'-'.$parts[1].' '  . $todayTimeLimit->end,
                    'disable' => $todayTimeLimit->disable,
                ));
            }
            $data["todayTimeLimit"] = $timeLimits;
            
            if(!$machine) {
                return response()->json(["status" => 200, "data" => $data, "message" => "logout"], 200);
            }
            
            if (strcmp($machine->password, $request->password) !== 0){
                return response()->json(["status" => 200, "data" => $data, "message" => "logout"], 200);
            }

            return response()->json(["status" => 200, "data" => $data, "message" => ""], 200);
        } else {
            return response()->json(["status" => 200, "data" => null, "message" => ""], 200);
        }
    }

    public function getMachines(Request $request)
    {
        $machines = Machine::all();
        foreach ($machines as $machine) {
            if(strtotime("now") - intval($machine->last_ping) > 11) {
                Machine::find($machine->id)->update([
                    'is_online' => false
                ]);
            }
        }

        return response()->json(["status" => 200, "data" => $machines, "message" => ""], 200);
    }

    public function deleteMachine(Request $request)
    {
        $validator = Validator::make($request->all(), [
    		'id' => 'required',
    	]);

    	if ($validator->fails()) {
    		return response()->json(["status" => 400, "message" => config('messages.required_param')], 200);
        }
        $machine = Machine::find($request->id);
        if ($machine) {
            $machine->delete();
        }
        $machines = Machine::all();

        return response()->json(["status" => 200, "data" => $machines, "message" => ""], 200);
    }

    public function getOnlineStatus(Request $request)
    {
        $data["machines"] = Machine::all();
        $data["online"] = Machine::where('is_online', true)->get();
        foreach($data['online'] as $online) {
            $machine = Machine::find($online->id);
            if(strtotime("now") - intval($machine->last_ping) > 11) {
                $machine->is_online = false;
                $machine->save();
            }
        }
        $data["offline"] = Machine::where('is_online', false)->get();

        return response()->json(["status" => 200, "data" => $data, "message" => ""], 200);
    }

    public function getCommissions(Request $request)
    {
        $data["commissions"] = Machine::select('id', 'machine_number', 'commission')
                                    ->orderBy('machine_number', 'ASC')
                                    ->get();
        
        return response()->json(["status" => 200, "data" => $data, "message" => ""], 200);
    }

    public function saveCommissionsChange(Request $request)
    {
        $validator = Validator::make($request->all(), [
    		'commissions' => 'required',
    	]);

    	if ($validator->fails()) {
    		return response()->json(["status" => 400, "message" => config('messages.required_param')], 200);
        }

        $commissions = $request->commissions;
        foreach($commissions as $commission) {
            $machine = Machine::find($commission['id']);
            $machine->commission = $commission['commission'];
            $machine->save();
        }

        return response()->json(["status" => 200, "data" => '', "message" => "success"], 200);
    }
}
